import _ from 'underscore';
import Mn from 'backbone.marionette';
import FormBehavior from "../../base/behaviors/FormBehavior.js";
import CheckboxListWidget from '../../widgets/CheckboxListWidget.js';
import DateWidget from '../../widgets/DateWidget.js';
import TextAreaWidget from '../../widgets/TextAreaWidget.js';
import InputWidget from '../../widgets/InputWidget.js';
import Radio from 'backbone.radio';
import Validation from 'backbone-validation';
import SelectWidget from '../../widgets/SelectWidget.js';

var template = require("./templates/CommonView.mustache");


const CommonView = Mn.View.extend({
    /*
     * Wrapper around the component making part of the 'common'
     * invoice/estimation form, provide a main layout with regions for each
     * field
     */
    behaviors: [{
        behaviorClass: FormBehavior,
        errorMessage: "Vérifiez votre saisie"
    }],
    tagName: 'div',
    className: 'separate_block border_left_block',
    template: template,
    fields: [
        'date',
        'address',
        'description',
        'validity_duration',
        'workplace',
        'start_date',
        'end_date',
        'first_visit',
        'mentions',
        'insurance_id',
    ],
    ui: {
        'moreAccordion': '#common-more'
    },
    regions: {
        errors: '.errors',
        date: '.date',
        address: '.address',
        description: '.description',
        validity_duration: '.validity_duration',
        workplace: '.workplace',
        start_date: '.start_date',
        mentions: '.mentions',
        insurance_id: '.insurance_id',
        first_visit: ".first_visit",
        end_date: '.end_date',
    },
    childViewTriggers: {
        'change': 'data:modified',
        'finish': 'data:persist'
    },
    modelEvents: {
        'validated:invalid': 'showErrors',
        'validated:valid': 'hideErrors',
        'saved': 'renderField'
    },
    events: {
        'focusout .validity_duration': "OnValidityDurationFocusOut"
    },
    initialize(options) {
        this.section = options['section'];
        let channel = Radio.channel('facade');
        this.listenTo(channel, 'bind:validation', this.bindValidation);
        this.listenTo(channel, 'unbind:validation', this.unbindValidation);

        let config = Radio.channel('config');
        this.mentions_options = config.request(
            'get:options', 'mentions'
        );
        this.insurance_options = config.request(
            'get:options', 'insurance_options'
        );
    },
    OnValidityDurationFocusOut() {
        if (_.isEmpty(this.model.get('validity_duration'))) {
            const default_duration = Radio.channel('config').request(
                'get:options', 'estimation_validity_duration_default'
            );
            this.model.set('validity_duration', default_duration);
            this.onRender();
        }
    },
    showErrors(model, errors) {
        this.$el.addClass('error');
    },
    hideErrors(model) {
        this.$el.removeClass('error');
    },
    bindValidation() {
        Validation.bind(this);
    },
    unbindValidation() {
        Validation.unbind(this);
    },
    getMentionIds() {
        var mention_ids = this.model.get('mentions');
        return mention_ids;
    },
    isMoreSet() {
        var mention_ids = this.getMentionIds();
        if (mention_ids.length > 0) {
            return true;
        }
        return false;
    },
    hasAvailableMentions() {
        return this.mentions_options.length > 0;
    },
    templateContext() {
        return {
            is_more_set: this.isMoreSet(),
            has_available_mentions: this.hasAvailableMentions(),
        };
    },
    showDate() {
        this.showChildView('date', new DateWidget({
            value: this.model.get('date'),
            title: "Date",
            field_name: "date",
            required: true
        }));
    },
    showAddress() {
        this.showChildView('address', new TextAreaWidget({
            title: 'Adresse du client',
            value: this.model.get('address'),
            field_name: 'address',
            rows: 4
        }));
    },
    showDescription() {
        this.showChildView('description', new TextAreaWidget({
            title: 'Objet du document',
            value: this.model.get('description'),
            field_name: 'description',
            rows: 4,
            required: true,
        }));
    },
    showValidityDuration() {
        if (!this.hasRegion('validity_duration')) {
            // We already destroyed the region
            return;
        }
        const field_def = this.section.validity_duration;
        if (field_def) {
            let default_duration = Radio.channel('config').request(
                'get:options', 'estimation_validity_duration_default'
            );
            let description = ""
            if (default_duration) {
                description = "Prend la valeur par défaut de la CAE si vide : " + default_duration
            }
            this.showChildView('validity_duration', new InputWidget({
                title: field_def.title,
                value: this.model.get('validity_duration'),
                description: description,
                field_name: 'validity_duration',
                required: field_def.required,
            }));
        } else {
            this.getRegion('validity_duration').destroy()
        }
    },
    showWorkplace() {
        if (!this.hasRegion('workplace')) {
            // We already destroyed the region
            return;
        }
        const field_def = this.section.workplace;
        if (field_def) {
            this.showChildView('workplace', new TextAreaWidget({
                title: field_def.title,
                value: this.model.get('workplace'),
                field_name: 'workplace',
                required: field_def.required,
                rows: 3
            }));
        } else {
            this.getRegion('workplace').destroy();
        }
    },
    showFirstVisit() {
        if (!this.hasRegion('first_visit')) {
            // We already destroyed the region
            return;
        }
        const field_def = this.section.first_visit;
        if (field_def) {
            this.showChildView('first_visit', new DateWidget({
                date: this.model.get('first_visit'),
                title: field_def.title,
                field_name: "first_visit",
                required: field_def.required,
                default_value: "",
            }));
        } else {
            this.getRegion('first_visit').destroy()
        }
    },
    showStartDate() {
        if (!this.hasRegion('start_date')) {
            // We already destroyed the region
            return;
        }
        const field_def = this.section.start_date;
        if (field_def) {
            this.showChildView('start_date', new DateWidget({
                date: this.model.get('start_date'),
                title: field_def.title,
                field_name: "start_date",
                required: field_def.required,
                default_value: "",
            }));
        } else {
            this.getRegion('start_date').destroy();
        }
    },
    showEndDate() {
        if (!this.hasRegion('end_date')) {
            // We already destroyed the region
            return;
        }
        const field_def = this.section.end_date;
        if (field_def) {
            this.showChildView('end_date', new InputWidget({
                value: this.model.get('end_date'),
                title: field_def.title,
                field_name: 'end_date',
                required: field_def.required,
            }));
        } else {
            this.getRegion('end_date').destroy()
        }
    },
    showMentionList() {
        if (!this.hasRegion('mentions')) {
            // We already destroyed the region
            return;
        }
        if (this.hasAvailableMentions()) {
            const mention_list = new CheckboxListWidget({
                options: this.mentions_options,
                value: this.getMentionIds(),
                title: "",
                field_name: "mentions",
                layout: "two_cols",
            });
            this.showChildView('mentions', mention_list);
        } else {
            this.getRegion('mentions').destroy()
        }
    },
    showInsurance() {
        if (!this.hasRegion('insurance_id')) {
            // We already destroyed the region
            return;
        }
        const field_def = this.section.insurance_id;
        if ((field_def) && (this.insurance_options.length > 0)) {
            const insurance_select = new SelectWidget({
                options: this.insurance_options,
                value: this.model.get('insurance_id'),
                title: field_def.title,
                field_name: "insurance_id",
                id_key: 'id',
                placeholder: "Sélectionnez",
                // TODO: éditable sous conditions (facture généré depuis un devis ou avoir)
                editable: field_def.edit,
                required: field_def.required,
            })
            this.showChildView('insurance_id', insurance_select);
        } else {
            this.getRegion('insurance_id').destroy()
        }
    },
    onRender() {
        this.showDate();
        this.showValidityDuration();
        this.showAddress();
        this.showDescription();
        this.showFirstVisit();
        this.showStartDate();
        this.showEndDate();
        this.showWorkplace();
        this.showMentionList();
        this.showInsurance();
    },
    renderField(values) {
        if (values instanceof Object) {
            if ('date' in values) {
                this.showDate();
            }
            if ('validity_duration') {
                this.showValidityDuration();
            }
            if ('address' in values) {
                this.showAddress();
            }
            if ('description' in values) {
                this.showDescription();
            }
            if ('start_date' in values) {
                this.showStartDate();
            }
            if ('first_visit' in values) {
                this.showFirstVisit();
            }
            if ('end_date' in values) {
                this.showEndDate();
            }
            if ('workplace' in values) {
                this.showWorkplace();
            }
            if ('mentions' in values) {
                this.showMentionList();
            }
            if ('insurance_id' in values) {
                this.showInsurance();
            }
        } else {
            this.onRender();
        }
    }
});
export default CommonView;